import store from '@/store'
import {
  showToast
} from './feedback.js'

import {
  API_BASE,
  NETWORK_TIMEOUT,
  DEFAULT_ERR_MESSAGE,
  PLATFORM,
  NETWORK_ERR_MESSAGE
} from '@/config'

//import service from './service';


async function handleRequest(url, opts) {
  opts.data.platform = PLATFORM.platform
  opts.data.appId = PLATFORM.appid
  var err = null
  var res = null
  
  let request_url = `${API_BASE}${url}`

  try {
    res = await uni.request({
      url: request_url,
      header: {
        'content-type': opts.contentType || 'application/x-www-form-urlencoded;charset=utf-8',
        'session-code': opts.sessionId || '',
      },
      method: opts.method || 'POST',
      timeout: opts.timeout || NETWORK_TIMEOUT,
      data: opts.data || {},
      sslVerify: false,
    })
  } catch (e) {
    err = e;
  }
  
  //showToast(request_url)
  //showToast(JSON.stringify(res.data))

  //console.info('接口结果：', url, err, JSON.stringify(res))
  return new Promise((resolve, reject) => {
    if (err) {
      if (opts.handleFail !== false) {
        showToast(NETWORK_ERR_MESSAGE)
        reject(err)
      }
    } else {
      // 404, 502等服务器错误信息
      if (typeof res.data !== 'object') {
        res.data = {
          status: res.statusCode,
          message: DEFAULT_ERR_MESSAGE,
          data: res.data
        }
      }
      // 正常处理
      if (res.data.success) {
        resolve(res.data)
      }
      // 未登录处理
      else if (res.data.errorCode === 'user-not-login') { // 未登录或者登录失效
        showToast('请先登录', 1000)
        store.dispatch('user/logout');
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }
      // 其他错误处理
      else {
        if (opts.handleFail !== false) {
          showToast(res.data.message || DEFAULT_ERR_MESSAGE, 2000)
        }
        reject(res)
      }
    }
  })
}

/**
 * 基本的http请求
 * @param {url: String} 请求的链接
 * @param {opts.data: Object} 请求的参数
 * @param {opts.needAuth: Boolean } 是否需要登录
 * @param {opts.handleFail: Boolean} 是否处理错误信息，设置为false将忽略请求时的错误
 * @param {opts.accessToken: Boolean} 是否将token覆盖为提供商token
 */
export async function request(url, opts = {}) {
  if (typeof opts.needAuth === 'undefined') {
    opts.needAuth = true;
  }
  opts.data = opts.data || {}
  if (opts.needAuth) {
    const userinfo = await store.dispatch('user/getLocalUser') // 获取用户信息
    opts.sessionId = store.getters.sessionId
  }
  return handleRequest(url, opts)
}

export function get(url, opts = {}) {
  opts.method = 'GET'
  return request(url, opts)
}

export function post(url, opts = {}) {
  opts.method = 'POST'
  return request(url, opts)
}

export async function upload(url, filePath, opts = {}) {
  if (typeof opts.needAuth === 'undefined') {
    opts.needAuth = true;
  }
  opts.data = opts.data || {}
  if (opts.needAuth) {
    const userinfo = await store.dispatch('user/getLocalUser') // 获取用户信息
    opts.sessionId = store.getters.sessionId
  }
  
  opts.data.platform = PLATFORM.platform
  opts.data.appId = PLATFORM.appid
  var err = null
  var res = null
  let request_url = `${API_BASE}${url}`
  
  try {
    res = await uni.uploadFile({
      url: request_url,
      filePath: filePath,
      name: 'file',
      header: {
        'session-code': opts.sessionId,
      },
    });
  } catch (e) {
    err = e;
  }
  
  if (res.errMsg != "uploadFile:ok") {
    err = res.errMsg
  }
  
  //showToast(request_url)
  console.log("upload-res:", res)
  
  return new Promise((resolve, reject) => {
    if (err) {
      if (opts.handleFail !== false) {
        showToast(NETWORK_ERR_MESSAGE)
        reject(err)
      }
    } else {
      // 404, 502等服务器错误信息
      if (typeof res.data !== 'object') {
        res.data = JSON.parse(res.data)
      }
      // 正常处理
      if (res.data.success) {
        resolve(res.data)
      }
      // 未登录处理
      else if (res.data.errorCode === 'user-not-login') { // 未登录或者登录失效
        showToast('请先登录', 1000)
        store.dispatch('user/logout');
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }
      // 其他错误处理
      else {
        if (opts.handleFail !== false) {
          showToast(res.data.message || DEFAULT_ERR_MESSAGE, 2000)
        }
        reject(res)
      }
    }
  })
}

function install(app) {
  app.config.globalProperties.$request = request
  app.config.globalProperties.$get = get
  app.config.globalProperties.$post = post
  app.config.globalProperties.$upload = upload
}
export default {
  install
}
